exports.abortOnError = ({ctx, error = {}, code = error.code, message = error.message}) => {
  if (code) {
    ctx.body = {
      code,
      message
    }
    return true
  }
}

exports.genAppError = ({ctx}) => {
  return (error) => {
    ctx.app.logger.info(error)
    return error
  }
}

exports.catchPromiseError = (e) => {
  this.ctx.app.logger.info(error)
  return error
}

exports.rules = {
  OffsetValidationRule: {
    offset: {
      type: 'int',
      required: true,
      min: 0
    },
    size: {
      type: 'int',
      required: true,
      max: 1000
    }
  }
}

exports.mongoose = {
  tranformId (doc, ret) {
    ret.id = ret._id;
    delete ret._id;
    return ret
  },

  tranformTime (doc, ret) {
    if (!ret.$time_fields) {
      ret.$time_fields = ['create_time', 'update_time']
    } else if (typeof ret.$time_fields === 'string') {
      ret.$time_fields = [ret.$time_fields]
    }

    if (ret.$time_fields instanceof Array) {
      let $time_fields = [].concat(ret.$time_fields)
      delete ret.$time_fields

      for (let fieldName of $time_fields) {
        if (ret.hasOwnProperty(fieldName) && ret[fieldName] instanceof Date) {
          ret[fieldName] = parseInt(ret[fieldName].getTime() / 1000)
        }
      }
    }

    return ret
  }
}

exports.rest = {
  resp ({ctx, error = {}, code = error.code || 0, message = error.message || '', data}) {
    // let body = { error_code: code, info: message, data }
    let body = { code, message, data }
    ctx.body = body

    return body
  },

  genProxyAdmin ({ctx}) {
    return function (req) {
      req.headers['Cookie'] = ctx.get('cookie')
    }
  },

  AuthProxyAdmin ({ctx, set_cookie}) {
    if (set_cookie instanceof Array) {
      set_cookie = set_cookie.join(' ');
    }

    if (set_cookie) {
      ctx.set('set-cookie', set_cookie);
    }
  },
}
